package handler

import (
	"github.com/gin-gonic/gin"
	"hotel-master/model"
	"strconv"
)

func Add(c *gin.Context) {
	title := c.PostForm("title")
	content := c.PostForm("content")
	userID, _ := strconv.Atoi(c.PostForm("user_id"))

	if title == "" || content == "" || userID == 0 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "字段不可为空",
		})
		return
	}
	data := model.Traver{
		Title:   title,
		Content: content,
		UserID:  userID,
	}
	err := model.DB.Create(&data).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "添加失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
	return
}

func Del(c *gin.Context) {
	var news model.Traver
	id := c.Query("id")
	err := model.DB.Delete(&news, id).Debug().Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "删除失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "删除成功",
	})
	return

}
func List(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	size, _ := strconv.Atoi(c.DefaultQuery("size", "5"))

	var count int64
	model.DB.Model(&model.Traver{}).Count(&count)
	offset := (page - 1) * size
	var video []model.Traver
	err := model.DB.Offset(offset).Limit(size).Find(&video).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "查询失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": gin.H{
			"count": count,
			"data":  video,
		},
	})
	return
}
